package com.example.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.user.mapper.UserMapper;
import com.example.user.pojo.User;
import com.example.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    // 用户名正则表达式
    private static final String USERNAME_REGEX = "^[a-zA-Z0-9_-]{4,16}$";
    // 邮箱正则表达式
    private static final String EMAIL_REGEX = "\\w+@(\\w+\\.)+\\w+";
    // 手机号正则表达式
    private static final String PHONE_REGEX = "^1[3456789]\\d{9}$";

    /**
     * 判断字符串是否为合法的用户名
     */
    public boolean isUserName(String str) {
        if (str == null) {
            return false;
        }
        return str.matches(USERNAME_REGEX);
    }
    /**
     * 判断字符串是否为合法的邮箱
     */
    public boolean isEmail(String str) {
        if (str == null) {
            return false;
        }
        return str.matches(EMAIL_REGEX);
    }
    /**
     * 判断字符串是否为合法的手机号
     */
    public boolean isPhoneNumber(String str) {
        if (str == null) {
            return false;
        }
        return str.matches(PHONE_REGEX);
    }

    @Override
    public Map<String, Object> login(User users) {
        Map<String, Object> map = new HashMap<>();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", users.getUserName());
        String userName = users.getUserName();
        String userEmail = users.getUserEmail();
        String userPhone = users.getUserPhone();

        boolean isUserName = isUserName(userName);
        boolean isPhone = isPhoneNumber(userEmail);
        boolean isEmail = isEmail(userPhone);
        //查询条件，通过用户名来查找用户
        if (isUserName) {
            queryWrapper.eq("user_name", userName);
        } else if (isEmail) {
            queryWrapper.eq("user_email", isEmail);
        } else if (isPhone) {
            queryWrapper.eq("user_phone", isPhone);
        }
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            map.put("state", "nource");
        } else {
            //有用户，判断密码是否正确
            if (user.getPassword().equals(users.getPassword())) {
                map.put("state", "success");
            } else {
                map.put("state", "error");
            }
        }
        return map;
    }
}
